namespace Warehouse

open System.Collections
open System.Collections.ObjectModel
open System.Windows.Data
open System.Windows.Controls
open FSharp.Windows
open Warehouse.Controls

type Catalog = LocalReports.CatalogDataSet.CatalogDataTable

type CatalogReportEvents = 
    | Print of IList * (unit -> unit)

[<AbstractClass>]
type CatalogReportModel() = 
    inherit Model()

    abstract Brands : DataModel.Brand seq with get, set
    abstract IsOperationInProgress : bool with get, set

type CatalogReporView() as this = 
    inherit View<CatalogReportEvents, CatalogReportModel, CatalogReportWindow>()
    
    let brands = this.Control.Brands
    do 
        brands.DisplayMemberPath <- "Name"
        brands.SelectionMode <- SelectionMode.Multiple
        this.Control.SelectAll.Click.Add(fun _ -> brands.SelectAll())

    override this.EventStreams = 
        [
            this.Control.Print.ClickToValue(Print(brands.SelectedItems, this.OK))
        ] 

    override this.SetBindings model =
        Binding.FromExpression 
            <@
                brands.ItemsSource <- model.Brands
            @>        
      
type CatalogReportController(repository : DataModel.Repository) = 
    inherit Controller<CatalogReportEvents, CatalogReportModel>()

    override this.InitModel model =
        model.Brands <- repository.Brands |> Seq.sortBy(fun brand -> brand.Name)

    override this.Dispatcher = function
        | Print(selectedBarnds, ok) -> Sync(this.Print selectedBarnds ok)

    member this.Print selectedBrands ok model = 
        model.IsOperationInProgress <- true

        let catalog = new Catalog()
        for brand in selectedBrands |> Seq.cast<DataModel.Brand> do
            for product in brand.Products() do
                let row = catalog.NewCatalogRow()
                row.Brand <- product.ProductName.Brand.Name
                row.Product <- product.ProductName.Name
                row.Size <- (sprintf "%s %s" product.SizeOrColor  product.Unit.Name).TrimStart()
                row.Shop <- product.ShopCost 
                row.SKU <- product.SKU
                row.QTY <- product.UPCs |> Seq.sumBy repository.AvailableQuantityByUPC
                catalog.AddCatalogRow row

        ReportForm.ShowLocalReportDialog("Warehouse.LocalReports.Catalog.rdlc", catalog)

        model.IsOperationInProgress <- false

        ok()

        